<template>
  <div style="margin-bottom: 18px; border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="overflow-y: hidden; height: 200px"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      @onCreated="onCreated"
      @onChange="onChange"
      :mode="mode"
    />
  </div>
  <!-- :mode="mode"  必要时添加在Toolbar 和 Editor中 -->
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, watch, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('')

const mode = 'default'
// 模拟 ajax 异步获取内容
onMounted(() => {
  valueHtml.value = ''
})

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

watch(valueHtml, (newValue) => {
  const context = `<p>${newValue}</p>`
  editorRef.value.setHtml(context)
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editorRefInstance = editorRef.value
  if (editorRefInstance) {
    editorRefInstance.destroy()
  }
})

function onCreated(editorRefInstance) {
  editorRef.value = Object.seal(editorRefInstance) // 记录 editor 实例，重要！
  editorRef.value.setHtml(`<p>${valueHtml.value}</p>`)
}

function onChange(editorRefInstance) {
  const text = editorRefInstance.getText()
  valueHtml.value = text
}
</script>
